package com.zrrd.gmall.user.controller;

import com.alibaba.fastjson.JSONObject;
import com.zrrd.gmall.common.result.Result;
import com.zrrd.gmall.common.util.IpUtil;
import com.zrrd.gmall.model.user.UserInfo;
import com.zrrd.gmall.service.constant.RedisConst;
import com.zrrd.gmall.user.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/api/user/passport")
public class UserApiController {

    @Autowired
    private UserService userService;
    @Autowired
    private RedisTemplate redisTemplate;

    //登录
    @PostMapping("/login")
    public Result login(@RequestBody UserInfo userInfo, HttpServletRequest request) {
        System.out.println("登录收到的参数=====>" + userInfo);
        //调用业务层的登录
        UserInfo info = userService.login(userInfo);
        //非空判断
        if (info != null) {
            //使用UUID生成一个token
            String token = UUID.randomUUID().toString().replaceAll("-", "");
            //新建Map集合 存入用户的昵称 和 token（前端需要）
            Map<String, Object> map = new HashMap<>();
            map.put("nickName", info.getNickName());
            map.put("token", token);

            //将用户信息存入到Redis
            JSONObject userJson = new JSONObject();
            userJson.put("userId", info.getId().toString());
            userJson.put("ip", IpUtil.getIpAddress(request));
            redisTemplate.opsForValue().set(RedisConst.USER_LOGIN_KEY_PREFIX + token, userJson.toJSONString(),
                    RedisConst.USERKEY_TIMEOUT, TimeUnit.SECONDS);
            //返回
            return Result.ok(map);
        } else {
            //提示错误信息
            return Result.fail().message("用户不存在或密码错误");
        }
    }

    //退出登录
    @GetMapping("/logout")
    public Result logout(HttpServletRequest request) {
        //获取请求头中的token
        String token = request.getHeader(" token");
        //将登录成功时 存在Redis中的用户信息删除掉
        redisTemplate.delete(RedisConst.USER_LOGIN_KEY_PREFIX + token);
        //返回结果
        return Result.ok();
    }


}
